<template>
  <div class='container'>
    <el-card class="box-card">
      <div slot="header" class="clearfix"
           v-if="isSubjectCome">
        <!-- 面包屑导航 -->
        <el-breadcrumb
                       separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>学科管理
          </el-breadcrumb-item>
          <el-breadcrumb-item>
            {{ $route.query.name }}
          </el-breadcrumb-item>
          <el-breadcrumb-item>目录管理
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-row :gutter="20" type="flex">
        <!-- 搜索 -->
        <el-col class="header-left">
          <el-form :inline="true"
                   :model="queryInfo"
                   class="demo-form-inline"
                   ref="searchForm"
                   size="small">
            <el-form-item label="目录名称"
                          class="search-input"
                          prop="directoryName">
              <el-input
                        v-model="queryInfo.directoryName">
              </el-input>
            </el-form-item>
            <el-form-item label="状态"
                          prop="state">
              <el-select v-model="queryInfo.state"
                         placeholder="请选择">
                <el-option label="已启用"
                           value="1">
                </el-option>
                <el-option label="已禁用"
                           value="0">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                         @click="onClear">清除
              </el-button>
              <el-button type="primary"
                         @click="onSeach">搜索
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <!-- 新增及返回按钮 -->
        <el-col class="header-right">
          <el-button class="back-btn"
                     type="success"
                     icon="el-icon-back"
                     size="small"
                     v-if="isSubjectCome"
                     @click="$router.back()">
            返回学科
          </el-button>
          <el-button class="add-btn"
                     type="success"
                     icon="el-icon-edit"
                     size="small"
                     @click="addHandler">
            新增目录
          </el-button>
        </el-col>
      </el-row>
      <!-- alert提示信息 -->
      <el-alert
                :title="`共有${cloneDirectotryData.counts}条数据`"
                type="info"
                class="alert"
                :closable="false"
                show-icon></el-alert>
      <!-- 表格 -->
      <el-table
                :data="cloneDirectotryData.items"
                fit
                highlight-current-row
                style="width: 100%">
        <el-table-column align="center"
                         type="index"
                         label="序号">
        </el-table-column>
        <el-table-column align="center"
                         label="所属学科"
                         prop="subjectName">
        </el-table-column>
        <el-table-column align="center"
                         label="目录名称"
                         prop="directoryName">
        </el-table-column>
        <el-table-column align="center"
                         label="创建者"
                         prop="username">
        </el-table-column>
        <el-table-column align="center"
                         label="创建日期"
                         prop="addDate"
                         :formatter="dateFormat">
        </el-table-column>
        <el-table-column align="center"
                         label="面试题数量"
                         prop="totals">
        </el-table-column>
        <el-table-column align="center"
                         label="状态"
                         prop="state"
                         :formatter="stateFormat">
        </el-table-column>
        <!-- 操作按钮 -->
        <el-table-column
                         align="center"
                         label="操作"
                         width="280"
                         class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary"
                       size="mini"
                       @click="handleStatus(scope.row)">
              <span
                    v-if="scope.row.state===0">启用</span>
              <span v-else>禁用</span>
            </el-button>
            <el-button type="primary"
                       size="mini"
                       @click="editDirectory(scope.row)"
                       :disabled="scope.row.state!==0">
              编辑</el-button>
            <el-button
                       size="mini"
                       type="danger"
                       :disabled="scope.row.state!==0"
                       @click="removeDirectory(scope.row.id)">
              删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <div class="pages">
          <el-pagination
                         background
                         @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page="Number(queryInfo.page)"
                         :total="Number(cloneDirectotryData.counts)"
                         :page-size="Number(queryInfo.pagesize)"
                         :page-sizes="[5, 10, 20, 30]"
                         layout="prev, pager, next, sizes, jumper">
          </el-pagination>
        </div>
      </div>
    </el-card>
    <!-- dialog对话框 -->
    <directorys-dialog
                       :title="isEdit ? '编辑目录': '新增目录'"
                       :dialogFormVisible="dialogVisible"
                       :subjectList="$store.state.directorys.simpleSubjectsList"
                       :isEdit="isEdit"
                       :isSubjectCome="isSubjectCome"
                       :currentRowData="currentRowData"
                       @cancel="dialogVisible = false"
                       @confirm="onConfirm" />
  </div>
</template>

<script>
// 引入请求函数
import * as api from '@/api/hmmm/directorys'
// 导入时间时间格式化过滤器
import { parseTimeByString } from '@/filters'
// 导入 lodash 深拷贝函数
import { cloneDeep, omitBy, isEmpty, isNumber } from 'lodash'
// 导入 dialog 弹出框
import DirectorysDialog from '../components/directorys-dialog.vue'
export default {
  data () {
    return {
      // 搜索参数
      queryInfo: {
        directoryName: '',
        state: null,
        subjectID: null,
        page: 1,
        pagesize: 10
      },
      // 克隆的目录信息
      cloneDirectotryData: {},
      // 对话框显示隐藏
      dialogVisible: false,
      // 是否为编辑状态
      isEdit: false,
      // 当前行数据
      currentRowData: {},
      // 是否从学科页面跳转过来
      isSubjectCome: false
    }
  },
  components: {
    DirectorysDialog
  },
  methods: {
    // 搜索
    onSeach () {
      this.refresh(this.queryInfo)
    },
    // 清空按钮
    onClear () {
      this.$refs.searchForm.resetFields()
    },
    // 点击编辑按钮
    editDirectory (row) {
      this.currentRowData = cloneDeep(row)
      this.isEdit = true
      this.dialogVisible = true
    },
    // 点击新增按钮
    addHandler () {
      this.isEdit = false
      this.dialogVisible = true
    },
    // 删除当前行
    removeDirectory (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await api.remove({ id })
        this.withMsg(res, '删除')
        await this.refresh(this.queryInfo)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 状态格式化
    stateFormat (row, column, cellValue, index) {
      if (cellValue === 1) {
        return '已启用'
      } else {
        return '已禁用'
      }
    },
    // 时间格式化
    dateFormat (row, column, cellValue, index) {
      return parseTimeByString(cellValue)
    },
    // 刷新函数
    async refresh (data) {
      const filterData = omitBy(data, (value, key) => isEmpty(value) && !isNumber(value))
      await this.$store.dispatch('directorys/getDirectorysData', filterData)
      this.cloneDirectotryData = cloneDeep(this.$store.state.directorys.directorysData)
    },
    // 对话框确认按钮
    async onConfirm (form, directorysDialog) {
      if (this.isEdit) {
        const res = await api.update(form)
        this.withMsg(res, '编辑')
        this.dialogVisible = false
        directorysDialog.resetFields()
        await this.refresh(this.queryInfo)
      } else {
        const res = await api.add(form)
        this.withMsg(res, '添加')
        this.dialogVisible = false
        directorysDialog.resetFields()
        await this.refresh(this.queryInfo)
      }
    },
    // 切换pagesize
    async handleSizeChange (value) {
      this.queryInfo.pagesize = value
      await this.refresh(this.queryInfo)
    },
    // 点击页码
    async handleCurrentChange (value) {
      this.queryInfo.page = value
      await this.refresh(this.queryInfo)
    },
    // 状态切换
    async handleStatus (row) {
      if (row.state === 1) {
        const res = await api.changeState({ id: row.id, state: 0 })
        this.withMsg(res, '修改状态')
        row.state = 0
      } else {
        const res = await api.changeState({ id: row.id, state: 1 })
        this.withMsg(res, '修改状态')
        row.state = 1
      }
    },
    // 操作后提示消息
    withMsg (res, words) {
      if (res.status !== 200) return this.$message.error(`${words}失败`)
      this.$message.success(`${words}成功`)
    }
  },
  async mounted () {
    await this.refresh(this.queryInfo)
    await this.$store.dispatch('directorys/getSimpleSubjectsList')
  },
  // 判断是否是从学科页面跳转并有参数携带
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (from.name === 'subjects-list' && vm.$route.query.id) {
        vm.isSubjectCome = true
        vm.queryInfo.subjectID = vm.$route.query.id
        vm.onSeach()
      }
    })
  }
}
</script>

<style scoped lang='less'>
.container {
  margin: 10px;
}

.header-left {
  padding: 0 30px !important;

  .search-input {
    margin-right: 50px;
  }

  /deep/ .el-form-item__label {
    font-size: 14px;
  }
}

.header-right {
  text-align: right;

  .back-btn {
    background-color: #fff;
    border: none;
    color: #409eff;
    font-size: 14px;
  }
}

.el-table {
  margin-top: 20px;
}

.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
